package com.elm.service.impl;

import com.elm.mapper.BusinessMapper;
import com.elm.mapper.FoodMapper;
import com.elm.mapper.OrderDetailetMapper;
import com.elm.mapper.OrdersMapper;
import com.elm.mapper.UserMapper;
import com.elm.po.Business;
import com.elm.po.Food;
import com.elm.po.Orders;
import com.elm.po.User;
import com.elm.service.FoodService;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class FoodServiceImpl implements FoodService {
	@Autowired
	private FoodMapper foodMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private BusinessMapper businessMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;
	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;

	private String getCurrentUserType() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUserTypeFromToken(token);
	}

	private String getCurrentUserName() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUsernameFromToken(token);
	}

	@Override
	public List<Food> getFoodByBusinessId(int businessId) { // 用户查询出available，商家查询全出
		if ("USER".equals(getCurrentUserType())) {
			return foodMapper.getAvailableFoodByBusinessId(businessId); // 用户可查
		} else {
			return foodMapper.getAllFoodByBusinessId(businessId); // 商家与ADMIN可查,与此同时要验证这是对应商家的，其他商家不可
		}
	}

	@Override
	public List<Food> getAllReviewingFood() {
		if (!"ADMIN".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅管理员可查看待审核食品");
		}
		List<Food> foodList = foodMapper.getAllReviewingFood();
		for(Food food:foodList){
			food.setBusiness(businessMapper.getBusinessById(food.getBusinessId()));
		}
		return foodList;
	}

	@Override
	public Food updateFoodInfo(Food food) {
		food.setFoodName(foodMapper.getFoodById(food.getId()).getFoodName());
		if ("USER".equals(getCurrentUserType())) {
			throw new RuntimeException("权限不足：仅商家老板或ADMIN可修改食品信息");
		}
		if ("BUSINESS".equals(getCurrentUserType())) {
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(foodMapper.getFoodById(food.getId()).getBusinessId()));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
//			Business business = businessMapper.getBusinessById(foodMapper.getFoodById(food.getId()).getBusinessId());
//			if(business.getBusinessStatus().equals("reviewing") || business.getBusinessStatus().equals("banned") || business.getBusinessStatus().equals("offline")) {
//				throw new RuntimeException("错误：当前店铺状态(不在营业中)无法修改商品信息");
//			}
		}
		foodMapper.updateFoodStatus(food.getId(),"Deleted");
		food.setBusinessId(foodMapper.getFoodById(food.getId()).getBusinessId());
		foodMapper.createFood(food); // 新增，并且将原来的修改为删除
		return foodMapper.getFoodById(food.getId());
	}

	@Override
	public int createFood(Food food) {
		System.out.println(getCurrentUserType());
		if ("BUSINESS".equals(getCurrentUserType())) {
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(food.getBusiness().getId()));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
			
//			Business business = businessMapper.getBusinessById(food.getBusiness().getId());
//			if(business.getBusinessStatus().equals("reviewing") || business.getBusinessStatus().equals("banned") || business.getBusinessStatus().equals("offline")) {
//				throw new RuntimeException("错误：当前店铺状态(不在营业中)无法新增商品信息");
//			}
		}
		Food food2 = foodMapper.getFoodByNameByBusiness(food.getFoodName(), food.getBusiness().getId());
		if (food2 != null && !food2.getStatus().equals("Deleted")) {
			throw new RuntimeException("food重复");
		}
		food.setBusinessId(food.getBusiness().getId());
		return foodMapper.createFood(food);
	}

	@Override
	public Food getFoodByNameByBusiness(String foodName, Integer id) {
		return foodMapper.getFoodByNameByBusiness(foodName, id);
	}

	@Override
	public Food updateFoodStatus(Integer foodId, String status) {
		User user = userMapper.getUserByName(getCurrentUserName()); 
		Food food = foodMapper.getFoodById(foodId);
		Integer businessId =food.getBusinessId();
		if ("USER".equals(getCurrentUserType()) && !userMapper.getStaffWorkByStaffId(user.getId()).contains(businessId)) {         //排除普通USER
			throw new RuntimeException("权限不足：仅商家老板或staff或ADMIN可修改食品信息");
		}
		if("USER".equals(getCurrentUserType()) && !status.equals("available") && !status.equals("sold_out")) {           //staff仅可修改这两项
			throw new RuntimeException("权限不足：staff无权修改其他属性");
		}
		if("USER".equals(getCurrentUserType())) {           //此时只剩下staff了
			Business business = businessMapper.getBusinessById(foodMapper.getFoodById(foodId).getBusinessId());
			if(business.getBusinessStatus().equals("reviewing") || business.getBusinessStatus().equals("banned") || business.getBusinessStatus().equals("offline")) {
				throw new RuntimeException("错误：当前店铺状态(正常不在营业中)无法修改商品信息");
			}
		}
		if ("BUSINESS".equals(getCurrentUserType())) {
			User boss = userMapper.getUserByName(getCurrentUserName());
			List<Business> businessList = businessMapper.getBusinessListByUserId(boss.getId());
			boolean isAssociated = businessList.stream()
					.anyMatch(biz -> biz.getId().equals(foodMapper.getFoodById(food.getId()).getBusinessId()));
			if (!isAssociated) {
				throw new RuntimeException("错误：老板未关联此商家");
			}
			
			Business business = businessMapper.getBusinessById(foodMapper.getFoodById(foodId).getBusinessId());
			if(business.getBusinessStatus().equals("reviewing") || business.getBusinessStatus().equals("banned") || business.getBusinessStatus().equals("offline")) {
				throw new RuntimeException("错误：当前店铺状态(正常不在营业中)无法修改商品信息");
			}
		}
		foodMapper.updateFoodStatus(foodId,status);
		return foodMapper.getFoodById(food.getId());
	}

	@Override
	public List<Food> getAllFoodByOrder(Integer order) {
		System.out.println(getCurrentUserType());
		Orders orders = ordersMapper.getOrdersById(order);
		if (orders.getCustomerId() != userMapper.getUserIdByName(getCurrentUserName())) { // 用户查看历史订单
			throw new RuntimeException("权限不足：仅用户自己可查看自己的订单");
		}
		return orderDetailetMapper.getAllFoodByOrder(order);
	}

	@Override
	public Food getFoodById(int id) {
		return foodMapper.getFoodById(id);
	}
}